package xyz.zyt123.hikvideo.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;

public class JsonUtil {
  private static ObjectMapper mapper = new ObjectMapper();
  private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

  public JsonUtil() {
  }

  public static ObjectMapper getMapper() {
    return mapper;
  }

  public static String objectToJson(Object value) throws RuntimeException {
    if (value == null) {
      return null;
    } else {
      try {
        return mapper.writeValueAsString(value);
      } catch (Exception var2) {
        throw new RuntimeException(var2.getMessage());
      }
    }
  }

  public static <T> T jsonToObject(String json, Class<T> valueType) {
    if (StringUtils.isBlank(json)) {
      return null;
    } else {
      try {
        return mapper.readValue(json, valueType);
      } catch (Exception var3) {
        throw new RuntimeException(var3.getMessage());
      }
    }
  }

  public static <T> T jsonToObject(String json, TypeReference<T> typeReference) {
    Assert.notNull(typeReference, "typeReference");
    if (StringUtils.isBlank(json)) {
      return null;
    } else {
      try {
        return mapper.readValue(json, typeReference);
      } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }
  }

  public static String getFormJson(String json, String key) {
    if (StringUtils.isBlank(json)) {
      return null;
    } else {
      Map objectMap;
      try {
        objectMap = mapper.readValue(json, Map.class);
      } catch (IOException var4) {
        throw new RuntimeException(var4);
      }

      Object o = objectMap.get(key);
      return o == null ? null : o.toString();
    }
  }

  public static <T> T convert(Object obj, Class<T> valueType) {
    String json = objectToJson(obj);
    if (StringUtils.isBlank(json)) {
      return null;
    } else {
      try {
        return mapper.readValue(json, valueType);
      } catch (Exception var4) {
        throw new RuntimeException(var4.getMessage());
      }
    }
  }

  static {
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(fmt);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  }
}
